# -*- coding: utf-8 -*-
# @Time : 2022/1/5 11:05
# @Author : Limusen
# @File : demo_base_page_23

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait


class DemoBasePage:

    def __init__(self, driver):
        self.driver = driver

    def open_url(self, url):
        self.driver.get(url)

    def find_element(self, element_info):
        """
        通过分离处理的元素识别字典信息，返回一个元素
        :param element_info: 元素信息，字典类型{}
        :return: element对象
        """
        try:
            locator_type = element_info["locator_type"]
            locator_value = element_info["locator_value"]
            locator_timeout = element_info["timeout"]

            if locator_type == "name":
                locator_type = By.NAME
            elif locator_type == "css":
                locator_type = By.CSS_SELECTOR
            elif locator_type == "xpath":
                locator_type = By.XPATH
            elif locator_type == "id":
                locator_type = By.ID
            elif locator_type == "class":
                locator_type = By.CLASS_NAME
            elif locator_type == "linktext":
                locator_type = By.LINK_TEXT
            elif locator_type == "partiallink":
                locator_type = By.PARTIAL_LINK_TEXT
            elif locator_type == "tag":
                locator_type = By.TAG_NAME
            # 采用匿名函数 将元素存在x变量当中,然后去查找页面是否存在当前元素
            element = WebDriverWait(self.driver, locator_timeout).until(
                lambda x: x.find_element(locator_type, locator_value))
        except Exception:
            raise

        return element

    def click(self, element_info):
        # 优化
        element = self.find_element(element_info)
        element.click()

    def send_keys(self, element_info, text):
        # 优化
        element = self.find_element(element_info)
        element.send_keys(text)


if __name__ == '__main__':
    driver = webdriver.Chrome()
    db = DemoBasePage(driver)
    db.open_url("http://www.baidu.com")
    driver.implicitly_wait(10)

    # db.send_keys((By.XPATH, '//*[@id="kw"]'), "测试一下")
    # time.sleep(2)
    # db.click((By.XPATH, '//*[@id="su"]'))

    # 优化代码 读取excel中的数据
    element_info = {
        'input_text': {'element_name': '输入框', 'locator_type': 'xpath', 'locator_value': '//*[@id="kw"]',
                       'timeout': 5.0},
        'click_button': {'element_name': '点击按钮', 'locator_type': 'xpath', 'locator_value': '//*[@id="su"]',
                         'timeout': 5.0}}

    input_t = element_info['input_text']
    click_b = element_info['click_button']

    db.send_keys(input_t, "测试一下")
    db.click(click_b)
